<!DOCTYPE html>
<html>

<head>
  <title>RobotGPT</title>
  <!-- Add Material-UI CSS -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
  <style>
    /* Override Materialize default button color to use Material-UI blue color */
    .btn,
    .btn-large {
      background-color: #007bff;
    }
  </style>
</head>

<body>
  <div class="container">
    <h1>RobotGPT</h1>
    <p>Click the "Start Recording" button and speak your command. Then click the "Stop Recording" button to convert it
      to speech. Finally, click the "Send to Robot" button to send the voice command to the robot.</p>
    <a id="startBtn" class="btn-large waves-effect waves-light" onclick="startRecording()">Start Recording</a>
    <a id="stopBtn" class="btn-large waves-effect waves-light" onclick="stopRecording()">Stop Recording</a>
    <a id="sendBtn" class="btn-large waves-effect waves-light" onclick="sendToRobot()">Send to Robot</a>
    <div id="output" class="flow-text"></div>
  </div>

  <!-- Add Material-UI JS -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

  <script>
    // Global variables
    let recognition;
    let outputDiv;

    // Initialize the Web Speech API
    function initialize() {
      recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
      recognition.interimResults = true;
      recognition.continuous = true;
      recognition.lang = 'en-US';

      recognition.onresult = function (event) {
        let interimTranscript = '';
        for (let i = event.resultIndex; i < event.results.length; ++i) {
          if (event.results[i].isFinal) {
            // Append final transcript to output div
            outputDiv.innerHTML += '<p>' + event.results[i][0].transcript + '</p>';
          } else {
            // Append interim transcript to output div
            interimTranscript += event.results[i][0].transcript;
          }
        }

        // Display interim transcript in output div
        outputDiv.innerHTML = interimTranscript;
      };

      recognition.onerror = function (event) {
        console.error('Recognition error:', event.error);
      };
    }

 // Start recording
    function startRecording() {
      outputDiv = document.getElementById('output');
      outputDiv.innerHTML = '';
      recognition.start();
    }

    // Stop recording
    function stopRecording() {
      recognition.stop();
    }
    

    // Speak the given text
function speak(text) {
  let utterance = new SpeechSynthesisUtterance(text);
  // Initialize the TTS engine
    let tts_engine = new SpeechSynthesisUtterance();
    tts_engine.text = text//"Message received. Sending to ChatGPT.";
    window.speechSynthesis.speak(tts_engine);

  tts_engine.speak(utterance.text);
}
// Send to robot
async function sendToRobot() {
  let command = outputDiv.innerHTML;

  // Send the voice command to the robot for further processing
  try {
    let response = await fetch("http://192.168.191.147:5000/rosgpt", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
     
      body: new URLSearchParams({
        text_command: command
      }),
    });

    let jsonResponse = await response.json();
    console.log("Received response from robot:", jsonResponse);
    outputDiv.innerHTML += '<p>Robot response: ' + jsonResponse.response + '</p>';
    speak("Robot response: " + jsonResponse.response);
  } catch (error) {
    console.error("Error sending command to robot:", error);
  }
}

// Initialize the app
window.onload = function () {
  initialize();
};
  </script>
</body>
</html>